package com.epfresh.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.MinusRecordBean;
import com.epfresh.bean.MinusRecordBean.ContentBean.ListBean;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseApplication;
import com.epfresh.utils.FormatUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OrderMinusListActivity extends BaseActivity implements LoadMoreListView.IXListViewListener{
    private LoadMoreListView mListView;
    private ArrayList<MinusRecordBean.ContentBean.ListBean> list;
    Context mContext;
    MinusRecordAdapter adapter;
    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    private int requestSucceedCount = 0;
    private int PAGE_SIZE = 5;
    private TagPager tagPager = new TagPager();

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        list = new ArrayList<MinusRecordBean.ContentBean.ListBean>();

        mListView.setPullLoadEnable(true); // 设置可滑动
        mListView.setXListViewListener(this);// 设置滑动监听器
        mContext = this;
        adapter = new MinusRecordAdapter(this, list);
        mListView.setAdapter(adapter);
        baseback.setVisibility(View.VISIBLE);
        initHeadView();
        requestOrderList(0);
    }

    void initView(){
        setContentView(R.layout.activity_list_minus);
        mListView = (LoadMoreListView)findViewById(R.id.listview);
        basetitle.setText("减免退");
        rightbtn.setText("帮助");
        rightbtn.setOnClickListener(this);
        vException = findViewById(R.id.v_exception);
        mainView = findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }


    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }


    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView() {
        ptrFrameLayout = (PtrMdFrameLayout) findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    boolean refreshFlag = false;
    public void refresh() {
        mListView.resetNoMore();
        refreshFlag = true;
        requestOrderList(0);
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        requestOrderList( number + 1);
    }


    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            mListView.noMore();
        } else {
            mListView.stopLoadMore();
        }
    }


    OnRequestListener<ContentEntity<MinusRecordBean.ContentBean.ListBean>> onRequestListener = new OnRequestListener<ContentEntity<MinusRecordBean.ContentBean.ListBean>>() {
        @Override
        public ContentEntity<MinusRecordBean.ContentBean.ListBean> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<MinusRecordBean.ContentBean.ListBean>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.order_no, arg + "", HttpRequest.FAIL_DATA_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0){
                showProgressView();
            }
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<MinusRecordBean.ContentBean.ListBean>> response, Object tag) {
            showMainView();
            requestSucceedCount ++;
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                list.clear();
            }
            ContentEntity<MinusRecordBean.ContentBean.ListBean> orderResponse = response.getResponseElement();
            List<MinusRecordBean.ContentBean.ListBean> content = orderResponse.getContent();
            tagPager.setLast(orderResponse.getLast());
            tagPager.setNumber(orderResponse.getNumber());
            tagPager.setSize(orderResponse.getSize());
            tagPager.setTotalElements(orderResponse.getTotalElements());
            list.addAll(content);
            adapter.notifyDataSetChanged();
            if(orderResponse.getNumber()==0){
                if(refreshFlag) {
                    mListView.setSelection(0);
                    refreshFlag=false;
                }
            }
            updateViewStatus(requestTag);
            if(list.size()==0){
                showExceptionView(R.mipmap.order_no, "暂无订单", HttpRequest.FAIL_DATA_EMPTY);
            }

        }
    };


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
        }
    }

    private RequestTag requestTag = new RequestTag();
    String cgiName= "appOrder/jmtList";

    public void requestOrderList(int page) {

        RequestEntityPurchase<Map<String, String>> entity = new RequestEntityPurchase<>();
        Map<String, String> map = new HashMap<>();
        map.put("accountId",getUser().getAccountId());
        map.put("pageNumber", page + "");
        if(getIntent().getStringExtra("id")!=null&&!getIntent().getStringExtra("id").equals("")){
            //cgiName = "appOrder/jmtOrderList";
            map.put("orderId",getIntent().getStringExtra("id"));
        }
        entity.setCmd(AppPurchaseRouterConstant.cmd_order_jmt_list);
        entity.setParameters(map);
        requestTag.tag = AppPurchaseRouterConstant.cmd_order_jmt_list;
        requestTag.action = page;
        request(entity, requestTag, onRequestListener);
    }


    public class MinusRecordAdapter extends BaseAdapter implements View.OnClickListener{

        public Context context;

        public List<MinusRecordBean.ContentBean.ListBean> groupList;


        private AdapterView.OnItemClickListener onItemClickListener;

        public MinusRecordAdapter(Context context , List<MinusRecordBean.ContentBean.ListBean> list) {
            this.context = context;
            this.groupList = list;
        }

        public AdapterView.OnItemClickListener getOnItemClickListener() {
            return onItemClickListener;
        }

        public void setOnItemClickListener(AdapterView.OnItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }

        @Override
        public int getCount() {
            return groupList != null ?groupList.size():0;
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int groupPosition, View convertView, ViewGroup parent) {
            ViewHolder vh = null;
            if (convertView == null) {
                vh = new ViewHolder();
                convertView = LayoutInflater.from(context).inflate(R.layout.item_record_minus_child, null, false);
                vh.tv_order_type = (TextView) convertView.findViewById(R.id.tv_order_type);
                vh.order_no = (TextView) convertView.findViewById(R.id.order_no);
                vh.iv_logo = (ImageView) convertView.findViewById(R.id.iv_logo);
                vh.iv_promotion = (ImageView) convertView.findViewById(R.id.iv_promotion);
                vh.tv_type = (TextView) convertView.findViewById(R.id.tv_type);
                vh.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
                vh.tv_unit = (TextView) convertView.findViewById(R.id.tv_unit);
                vh.tv_activity_promotion =  convertView.findViewById(R.id.tv_activity_promotion);
                vh.tv_activity_second = convertView.findViewById(R.id.tv_activity_second);
                vh.tv_number = (TextView) convertView.findViewById(R.id.tv_number);
                vh.tv_total = (TextView) convertView.findViewById(R.id.tv_total);
                vh.tv_minus_money = (TextView) convertView.findViewById(R.id.tv_minus_money);
                vh.tv_minus_number = (TextView) convertView.findViewById(R.id.tv_minus_number);
                vh.ll_order_child = convertView.findViewById(R.id.ll_order_child);
                convertView.setTag(vh);
            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            MinusRecordBean.ContentBean.ListBean orders = groupList.get(groupPosition);
            vh.order_no.setText("减免退编号：" + orders.getJmtNo());
            ImageLoader.getInstance().displayImage(orders.getProductImgUrl(), vh.iv_logo);

            String promotionMarkUrl = orders.getMarkUrl();
            ImageLoader.getInstance().displayImage(promotionMarkUrl, new ImageViewAware(vh.iv_promotion), BaseApplication.getTagOptions(promotionMarkUrl) , null, null, null);
/*if(orders.getPromotionTypeTitle()!=null&&"秒杀".equals(orders.getPromotionTypeTitle())){
    vh.tv_promotion.setText("秒杀");
    vh.tv_promotion.setVisibility(View.VISIBLE);

    vh.tv_promotion.setBackgroundResource(R.drawable.seckill_tag_bg);
}else if(orders.getPromotionTypeTitle()!=null&&"促销".equals(orders.getPromotionTypeTitle())){
    vh.tv_promotion.setText("促销");
    vh.tv_promotion.setVisibility(View.VISIBLE);
    vh.tv_promotion.setBackgroundResource(R.drawable.promotion_tag_bg);
}else {
    vh.tv_promotion.setVisibility(View.GONE);
}*/
            String promotionType = orders.getPromotionType();
            if ("1".equals(promotionType)) {//1促销2秒杀
                vh.tv_activity_promotion.setVisibility(View.VISIBLE);
                vh.tv_activity_second.setVisibility(View.GONE);
            }else  if ("2".equals(promotionType)) {//1促销2秒杀
                vh.tv_activity_promotion.setVisibility(View.GONE);
                vh.tv_activity_second.setVisibility(View.VISIBLE);
            }else {
                vh.tv_activity_promotion.setVisibility(View.GONE);
                vh.tv_activity_second.setVisibility(View.GONE);
            }
           // vh.tv_unit.setText(orders.getProductPriceUnit());
            vh.tv_title.setText(orders.getProductTitle());
            //vh.tv_unit.setText(orders.getProductPriceUnit()+"("+orders.getProductPackageSize()+")");
            if (orders.getSpecName() == null || orders.getSpecName().equals("默认")) {
                vh.tv_number.setText(orders.getProductPriceUnit() + "   " + "X" + FormatUtil.subZeroAndDot(orders.getProductCount() + ""));
            } else {
                vh.tv_number.setText(orders.getSpecName() + "(" +orders.getProductPriceUnit()+")   "+"X" + FormatUtil.subZeroAndDot(orders.getProductCount() + ""));
            }

            vh.tv_total.setText(orders.getProductTotalPrice() + "元");
            vh.tv_minus_money.setText("减免退金额："+orders.getJmtTotalPrice()+"元");
            vh.tv_order_type.setText(orders.getJmtRefundStatusTitle());
            if(orders.getJmtProductCount()<=0){
                vh.tv_minus_number.setVisibility(View.GONE);
            }else{
                vh.tv_minus_number.setVisibility(View.VISIBLE);
                vh.tv_minus_number.setText("退货："+orders.getJmtProductCount()+orders.getProductChargeUnit());
            }
            if (2==(orders.getSalesType())) {//预售
                vh.tv_type.setVisibility(View.VISIBLE);
                String html="<font color=\"#00ffffff\">a预售】</font>"+orders.getProductTitle();
                vh.tv_title.setText(Html.fromHtml(html));
            } else {//现售
                vh.tv_type.setVisibility(View.GONE);
                vh.tv_title.setText(orders.getProductTitle());
            }

            vh.ll_order_child.setTag(R.id.item_key_position, orders.getId());
            vh.ll_order_child.setOnClickListener(this);
            return convertView;
        }

        @Override
        public void onClick(View v) {
            Object tag = v.getTag(R.id.item_key_position);
            if (tag != null && tag instanceof String) {
                String id = (String) tag;
                switch (v.getId()) {
                    case R.id.ll_order_child:
                        Intent detail = new Intent(context, OrderMinusDetailActivity.class);
                        detail.putExtra("id", id);
                        context.startActivity(detail);
                        break;
                }
            }
        }


        public class ViewHolder {
            TextView order_no;
            ImageView iv_promotion;
            ImageView iv_logo;
            TextView tv_type;
            TextView tv_title;
            TextView tv_unit;
            //TextView tv_promotion;
            TextView tv_order_type;
            TextView tv_activity_promotion,tv_activity_second;

            //holder.setText(R.id.tv_order_type, bean.getJmtRefundStatusTitle());

            TextView tv_number;
            TextView tv_total,tv_minus_number,tv_minus_money;
            View ll_order_child;
        }
    }

}
